<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-04-26
 * Time: 13:34
 */
namespace app\api\controller;

use think\Exception;
use  think\Request;
use think\Controller;

class Upload extends Controller
{
    protected function _initialize()
    {
        parent::_initialize();
    }

    /**
     * @param Request $request
     * @return \think\response\Json
     * 通用上传
     */
    public function uploadFile(Request $request)
    {

        foreach ($_FILES as $key => $value) {
            $file_key = $key;
        }
        $config = [
            'size' => 42949672960,
            'ext' => 'jpg,jpeg,gif,png,bmp,mp3,wav,wma,mp4,avi,wmv,rm,rmvb,mpg,mpeg,3gp,mov,flv,mkv,caf'
        ];

        $res_rules = $request->file($file_key)->check($config);

        if (empty($res_rules)) {
            $result = [
                'code' => 1,
                'message' => '文件验证不通过'
            ];
            return json($result);
        }

        try {
            //先上传到本地
            $info = $request->file($file_key)->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . "$file_key");
            if ($info) {
                $upload_file_path = $request->domain() . DS . 'uploads' . DS . "$file_key" . DS . $info->getSaveName();
                $result           = [
                    'code' => 0,
                    'msg' => "success",
                    'data' => [
                        "src" => $upload_file_path,
                        "title" => ''
                    ]
                ];
                return json($result);
            }
        } catch (Exception $exception) {
            $result = [
                'code' => 1,
                'msg' => $request->file($file_key)->getError(),
                'data' => [
                    "src" => '',
                    "title" => ''
                ]
            ];
            return json($result);
        }

    }




}